/*
 * test.c
 *
 *  Created on: Jun 16, 2017
 *      Author: gino
 */

#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"


/**解析、构建
 * {
 * 	"semantic":	{
 *		"slots":	{
 *			"name":	"张三"
 *		}
 *	},
 *	"rc":	0,
 *	"operation":	"CALL",
 *	"service":	"telephone",
 *	"text":	"打电话给张三"
 * }
 *
 **/

//以递归的方式打印 json
void printJson(cJSON *root) {
	for (int i = 0; i < cJSON_GetArraySize(root); ++i) {
		cJSON *item = cJSON_GetArrayItem(root, i);
		if (item->type == cJSON_Object) {
			printJson(item);
		} else {
		//	printf("key == %s\tvalue == %s\t", item->string, cJSON_PrintUnformatted(item));
			printf("%s -> ",item->string);
			switch(item->type){
			case cJSON_String :
				printf("%s\t",item->valuestring);
				break;
			case cJSON_Number :
				printf("%d\t",item->valueint);
				break;
			}
		}
	}
	printf("\n");
}

// 解析测试
void parseTest() {
	char * jsonStr =
			"{\"semantic\":{\"slots\":{\"name\":\"张三\"}},\"rc\":0,\"operation\":\"CALL\",\"service\":\"telephone\",\"text\":\"打电话给张三\"}";
	cJSON *root = cJSON_Parse(jsonStr);
	if (!root) {
		printf("Error before: [%s]\n", cJSON_GetErrorPtr());
		exit(EXIT_FAILURE);
	}

	cJSON *semantic_item = cJSON_GetObjectItem(root, "semantic");
	// 有格式的打印:
	printf("有格式的打印方式：\n%s\n", cJSON_Print(semantic_item));

	cJSON *slots_item = cJSON_GetObjectItem(semantic_item, "slots");
	// 无格式的打印:
	printf("无格式的打印方式：\n%s\n", cJSON_PrintUnformatted(slots_item));

	// 打印 键值对
	cJSON *name_item = cJSON_GetObjectItem(slots_item, "name");
	printf("key == %s\tvalue == %s\n", name_item->string,
			name_item->valuestring);

	printJson(root);


}


//构建测试
void createTest(){
	cJSON *root = cJSON_CreateObject();
	//cJSON *semantic_item = cJSON_CreateObject();
	cJSON *slots_item = cJSON_CreateObject();
	cJSON *name_item = cJSON_CreateObject();

	cJSON_AddItemToObject(name_item,"name",cJSON_CreateString("张三"));
	//cJSON_AddItemToObject(name_item,"cmd_arg",cJSON_AddItemToArray("张ss"));
	cJSON_AddItemToObject(slots_item,"slots",name_item);
	//cJSON_AddItemToObject(semantic_item,"semantic",slots_item);

	cJSON_AddItemToObject(root,"semantic",slots_item);
	cJSON_AddItemToObject(root,"rc",cJSON_CreateNumber(0));
	cJSON_AddItemToObject(root,"operation",cJSON_CreateString("CALL"));
	cJSON_AddItemToObject(root,"service",cJSON_CreateString("telephone"));
	cJSON_AddItemToObject(root,"text",cJSON_CreateString("打电话给张三"));


	//printf("\n\n%s\n\n",cJSON_Print(root));
	printf("\n\n%s\n\n",cJSON_PrintUnformatted(root));
	cJSON_Delete(root);	// 因为是链表结构，释放最外层即可.
	//cJSON_Delete(name_item);
}


int main() {

	parseTest();
	//createTest();

	return 0;
}
